<template>
    <!-- 筛选区 -->
    <div class="sub-filter">
        <div class="item" v-for="item in list" :key="item.id">
            <div class="head">{{ item.name }}：</div>
            <div class="body">
                <a href="javascript:;" @click="filterAttr(item, {})"
                    :class="{ active: item.activeName === undefined }">全部</a>
                <a href="javascript:;" :class="{ active: item.activeName === p.name }" v-for="p in item.properties"
                    :key="p.id" @click="filterAttr(item, p)">
                    {{ p.name }}
                </a>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'SubFilter',
}
</script>

<script setup>
import { computed, inject, reactive } from 'vue'
// 获取父组件的数据
const filterSubData = inject('filterSubData')

// 🔔 筛选区的列表数据其实包含两部分：品牌数据 + 销售规格
const list = computed(() => {
    return [
        reactive({ id: 'brands', name: '品牌', properties: filterSubData.value.brands }),
        ...filterSubData.value.saleProperties
    ]
})

const reqParams = inject('reqParams')
const filterAttr = (theItem, theItem2) => {
    // console.log(theItem, theItem2)
    const groupName = theItem.name
    const propertyName = theItem2.name
    // 👍 给一级对象添加收集到的数据，用于筛选区高亮
    theItem.activeName = propertyName
    // 获取筛选参数有两种情况：
    //  情况1. 获取品牌 id
    if (groupName === '品牌') {
        reqParams.brandId = theItem2.id
        return
    }
    //  情况2. 获取销售规格参数
    const attr = { groupName, propertyName }
    // 如果属性已经存在就修改属性的值，如果是不存在则追加
    const obj = reqParams.attrs.find(item => item.groupName === groupName)
    if (obj) {
        // 存在，修改
        obj.propertyName = propertyName
    } else {
        // 不存在：追加
        reqParams.attrs.push(attr)
    }
}
</script>

<style scoped lang="less">
// 筛选区
.sub-filter {
    background: #fff;
    padding: 25px;

    .item {
        display: flex;
        line-height: 40px;

        .head {
            width: 80px;
            color: #999;
        }

        .body {
            flex: 1;

            a {
                margin-right: 36px;
                transition: all 0.3s;
                display: inline-block;

                &.active,
                &:hover {
                    color: @xtxColor;
                }
            }
        }
    }
}
</style>